<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-20 11:24:04
 * @LastEditTime: 2023-02-16 10:11:37
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 合同明细
 * @Motto: Write the code. Change the world.
-->
<template>
  <div>
    <a-card
      class="clause-detail"
      :style="{ width: $store.getters.isMobile ? '1200px' : undefined }"
      v-for="clause of dataList"
      :key="clause.id"
      :title="clause.clause_title + '明细报表'"
    >
      <a-row class="cols header">
        <a-col :span="6">区间</a-col>
        <a-col :span="2">费用类型</a-col>
        <a-col :span="4">付款日</a-col>
        <a-col :span="3"
          >{{ isCostContract ? "最终单价" : "最终单价（含税）" }}
        </a-col>
        <a-col :span="3" v-if="!isCostContract">营业额</a-col>
        <a-col :span="3">
          {{ isCostContract ? "应付" : "应收（含税）" }}
        </a-col>
        <a-col :span="3" v-if="!isCostContract"> 税额 </a-col>
      </a-row>
      <a-collapse
        :bordered="false"
        style="background: #fff"
        v-if="clause.detail"
        v-model:activeKey="clause.activeKey"
      >
        <template #expandIcon="{ isActive }">
          <CaretRightOutlined :rotate="isActive ? 90 : 0" />
        </template>
        <a-collapse-panel
          v-for="item of clause.detail.list"
          :key="item.key"
          :header="item.title"
        >
          <a-alert
            class="alert"
            v-if="item.belong == 'divide'"
            show-icon
            message="录入营业额后会根据分成规则自动生成对应租期的账单。录入后不可修改，请谨慎填写!"
          />
          <template v-for="(listItem, listIndex) of item.list" :key="listIndex">
            <a-row class="cols">
              <a-col :span="6">
                <template v-if="item.belong != 'bond'">
                  <a-tag color="green" class="mr-5">
                    第{{ listItem.reportStage }}期
                  </a-tag>
                </template>
                <span> {{ listItem.startDate }} ~ {{ listItem.endDate }} </span>
                <a-popover title="不生成">
                  <template #content>
                    <span>
                      基于合同条款，该期租金账单取自固定
                      {{ item.belong == "lease" ? "分成" : "租金" }}账单
                    </span>
                  </template>
                  <ExclamationCircleOutlined
                    v-if="listItem.is_create == false"
                    style="color: #faad14; margin-left: 4px"
                  />
                </a-popover>
              </a-col>
              <a-col :span="2">{{ listItem.costTypeDesc }}</a-col>
              <a-col :span="4">{{ listItem.payDate }}</a-col>
              <a-col :span="3">
                {{ listItem.finalTaxUnitPrice || listItem.finalPrice || "--" }}
                {{ listItem.finalPriceUnit }}
              </a-col>
              <a-col :span="3" v-if="!isCostContract">
                <template
                  v-if="
                    item.belong == 'divide' &&
                    (!listItem.mdate || !listItem.mdate.length) &&
                    !listItem.hasReceivePrice
                  "
                >
                  <span
                    v-if="
                      listItem.takeHigh == 2 ||
                      (listItem.takeHigh == 0 &&
                        listItem.turnover &&
                        !listItem.edit)
                    "
                  >
                    {{ listItem.turnover + listItem.price_unit }}
                  </span>
                  <template v-else>
                    <template v-if="!listItem.edit">
                      <span>未录入</span>
                      <a-button
                        type="link"
                        style="margin-left: 4px"
                        @click="listItem.edit = true"
                        v-if="showDivideEdit"
                      >
                        <template #icon>
                          <EditOutlined />
                        </template>
                      </a-button>
                    </template>
                    <template v-else>
                      <a-input-number
                        :min="0"
                        v-model:value="listItem.turnover"
                        @change="handleTurnoverChange(clause, listItem)"
                      />
                      <a-button
                        type="link"
                        @click="handleEditCancel(listItem)"
                        style="margin-left: 16px"
                      >
                        取消
                      </a-button>
                      <a-button
                        type="link"
                        @click="handleEditsuccess(clause, listItem)"
                      >
                        保存
                      </a-button>
                    </template>
                  </template>
                </template>
                <span v-else>
                  {{
                    listItem.turnover
                      ? listItem.turnover + listItem.price_unit
                      : "--"
                  }}
                </span>
              </a-col>
              <a-col :span="3">
                {{ listItem.receivePrice + listItem.price_unit }}
              </a-col>
              <a-col :span="3" v-if="!isCostContract">
                <span v-if="!listItem.taxAmount && listItem.taxAmount != 0"
                  >--</span
                >
                <span v-else>{{
                  listItem.taxAmount + listItem.price_unit
                }}</span>
              </a-col>
            </a-row>
            <template v-if="listItem.mdate && listItem.mdate.length">
              <a-row
                class="cols"
                v-for="(mItem, mIndex) of listItem.mdate"
                :key="'mdate_' + mIndex"
              >
                <a-col :span="6">
                  <cu-icon type="org-fenzhi" style="font-size: 18px"></cu-icon>
                  <span class="ml-5">
                    {{ mItem.startDate }} ~ {{ mItem.endDate }}
                  </span>
                </a-col>
                <a-col :span="2">{{ mItem.costTypeDesc }}</a-col>
                <a-col :span="4">{{ mItem.payDate }}</a-col>
                <a-col :span="3">
                  {{ mItem.finalTaxUnitPrice || mItem.finalPrice || "--" }}
                  {{ mItem.finalPriceUnit }}
                </a-col>
                <a-col :span="3" v-if="!isCostContract">
                  <template
                    v-if="item.belong == 'divide'"
                    &&
                    !listItem.hasReceivePrice
                  >
                    <span
                      v-if="
                        mItem.takeHigh == 2 ||
                        (mItem.takeHigh == 0 && mItem.turnover && !mItem.edit)
                      "
                    >
                      {{ mItem.turnover + mItem.price_unit }}
                    </span>
                    <template v-else>
                      <template v-if="!mItem.edit">
                        <span>未录入</span>
                        <a-button
                          type="link"
                          style="margin-left: 4px"
                          @click="mItem.edit = true"
                          v-if="showDivideEdit"
                        >
                          <template #icon>
                            <EditOutlined />
                          </template>
                        </a-button>
                      </template>
                      <template v-else>
                        <a-input-number
                          :min="0"
                          v-model:value="mItem.turnover"
                          @change="
                            handleTurnoverChange(clause, listItem, mItem)
                          "
                        />
                        <a-button
                          type="link"
                          @click="handleEditCancel(mItem)"
                          style="margin-left: 16px"
                        >
                          取消
                        </a-button>
                        <a-button
                          type="link"
                          @click="handleEditsuccess(clause, listItem, mIndex)"
                        >
                          保存
                        </a-button>
                      </template>
                    </template>
                  </template>
                  <span v-else>--</span>
                </a-col>
                <a-col :span="3">
                  {{ mItem.receivePrice + mItem.price_unit }}
                </a-col>
                <a-col :span="3" v-if="!isCostContract">
                  <span v-if="!mItem.taxAmount && mItem.taxAmount != 0">
                    --
                  </span>
                  <span v-else>{{ mItem.taxAmount + mItem.price_unit }}</span>
                </a-col>
              </a-row>
            </template>
          </template>
        </a-collapse-panel>
      </a-collapse>
      <a-row v-if="showTotal">
        <a-col :span="24" class="cols cl-footer">
          <span class="mr-10"
            >费用应收总计： {{ clause.detail.receiveTotal }}元</span
          >
          <span>保证金应收总计： {{ clause.detail.bondTotal }}元</span>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, watch, ref, computed, toRaw, createVNode } from "vue";
import {
  CaretRightOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { useRoute } from "vue-router";
import store from "../../../store/index";
import { message, Modal } from "ant-design-vue";

export default defineComponent({
  name: "ContractClauseDetail",
  props: {
    active: {
      type: Boolean,
      default: false,
    },
    showType: {
      type: String,
      default: '',
    },
    drawerId: {
      type: [Number, String],
      default: '',
    },
  },
  components: { CaretRightOutlined, ExclamationCircleOutlined, EditOutlined },
  setup(props, context) {
    const $route = useRoute();
    const dataList = ref([]);
    const id = computed(() => props.showType === 'drawer' ? Number(props.drawerId) : Number($route.query.id));

    const getDetail = (refresh = false) => {
      if (!dataList.value.length || refresh) {
        request
          .get("/org", "/create/contractDetail", {
            id: id.value,
          })
          .then((res) => {
            if (res.data) {
              res.data.forEach((item) => {
                item.detail = utils.getClauseDetailByGroup(
                  item.report_detail,
                  item.attribute
                );
                item.activeKey = item.detail.list.map((item) => item.key);
              });
            }
            dataList.value = res.data;
            console.log(
              "------------getDetail 租金明细",
              toRaw(dataList.value)
            );

            getInfo();
          });
      }
    };

    const contractInfo = ref({});
    const isCostContract = ref(false);
    const getInfo = () => {
      request
        .get("/org", "/create/contractInfo", { id: id.value })
        .then((res) => {
          contractInfo.value = res;
          // 有业主信息是成本合同
          if (res.proprietor_id) {
            isCostContract.value = true;
            // 成本合同&&托管计租：不展示租金列表内容
            if (res.lease_mode == "unit2") {
              dataList.value.forEach((item) => {
                console.log(item);
                if (
                  item.detail &&
                  item.detail.list &&
                  item.detail.list.length
                ) {
                  item.detail.list.forEach((listItem, listIndex) => {
                    // 如果是租金
                    if (listItem.belong == "lease") {
                      item.detail.list.splice(listIndex, 1);
                    }
                  });
                }
              });
            }
          }
        });
    };

    // 是否展示总计信息
    const showTotal = computed(() => {
      for (let dataItem of dataList.value) {
        const {
          report_detail: { divideData },
        } = dataItem;
        if (divideData && divideData.length) {
          for (let item of divideData) {
            if (item.takeHigh != 0) {
              return false;
            }
          }
        }
      }
      return true;
    });

    const contractDetail = computed(() => store.getters.contractDetail);

    const showDivideEdit = computed(() => {
      const { op_type, status } = contractDetail.value;
      return op_type == 1 && [2, 10, 14].includes(Number(status));
    });

    // 修改营业额
    const handleTurnoverChange = (clause, currentItem, subItem) => {
      const { multiple_clause } = clause;
      const current = subItem || currentItem;
      current.group = current.group || currentItem.group;
      const ratioInfo = utils.getDivideRatio(multiple_clause, current);
      if (ratioInfo) {
        const result = utils.getRatioPrice(current, ratioInfo);
        current.receivePrice = result.receivePrice;
      }
    };

    // 取消修改
    const handleEditCancel = (currentItem) => {
      currentItem.turnover = 0;
      currentItem.receivePrice = 0;
      currentItem.edit = false;
    };

    // 保存修改
    const handleEditsuccess = (clause, currentItem, subIndex = -1) => {
      const { detail } = clause;
      // const { unit_price_point } = contractDetail.value;
      let current = currentItem;
      if (subIndex != -1) {
        current = currentItem.mdate[subIndex];
      }
      if (!current.turnover || current.turnover == 0) {
        Modal.info({
          content: "输入的营业额不可为0",
          centered: true,
        });
        return;
      }
      Modal.confirm({
        title: "确认提醒",
        content: `确认录入营业额为${current.turnover}${currentItem.price_unit}？`,
        okText: "确定",
        cancelText: "取消",
        centered: true,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: () => {
          current.edit = false;
          utils
            .setReceviePrice({
              leaseList: detail.list,
              currentItem,
              subIndex,
              // unitPoint: unit_price_point,
              needTotal: true,
            })
            .then((changedData) => {
              request
                .post("/org", "/contract/divideEntry", {
                  contract_id: Number(id.value),
                  report_id: clause.id,
                  group: currentItem.group,
                  reportStage: currentItem.reportStage,
                  reportData: {
                    leaseData: changedData.leaseItem
                      ? [changedData.leaseItem]
                      : [],
                    divideData: [currentItem],
                  },
                  needMsg: true,
                })
                .then((res) => {
                  message.success(res.msg || "录入成功！");
                  getDetail(true);
                });
            });
        },
        onCancel: () => {
          handleEditCancel(currentItem);
        },
      });
    };

    watch(
      () => props.active,
      (val) => {
        if (val) {
          getDetail();
        }
      }
    );

    return {
      dataList,
      showTotal,
      showDivideEdit,
      handleTurnoverChange,
      handleEditCancel,
      handleEditsuccess,
      contractInfo,
      isCostContract,
    };
  },
});
</script>

<style lang="less" scoped>
@colHeight: 40px;
.clause-detail {
  margin-bottom: 10px;
  .alert {
    margin: 0 10px 10px 10px;
  }
  &:deep(.ant-alert) {
    padding: 4px 16px;
  }
  &:deep(.ant-card-body) {
    padding: 0;
  }
  .header {
    background: @primary-color-bg;
  }
  .cols {
    line-height: @colHeight;
    padding: 0 12px;
  }
  .cl-footer {
    text-align: right;
    color: rgba(0, 0, 0, 0.8);
  }
}
</style>
